import http from "@/utils/http";

export const downloadSpeedDetection = ({ url, size }) => {
  return new Promise((resolve, reject) => {
    return new Promise((resolve, reject) => {
      const img = new Image();
      img.src = `${url}?_t=${Math.random()}`; // 加个时间戳以避免浏览器只发起一次请求
      const startTime = new Date();

      img.onload = function () {
        const fileSize = size; // 单位是 kb
        const endTime = new Date();
        const costTime = endTime - startTime;
        const speed = (fileSize / (endTime - startTime)) * 1000; // 单位是 kb/s
        resolve({ speed, costTime });
      };

      img.onerror = reject;
    });
  });
};

export const uploadSpeedDetection = (url, size = 10) => {
  return new Promise(async (resolve, reject) => {
    size = size * 1024 * 1024;
    const file = new Blob([new ArrayBuffer(size)], { type: "application/octet-stream" });
    const startTime = new Date();

    // 换算基数
    const onUploadProgress = (progressEvent) => {
      const costTime = new Date() - startTime;
      const speed = (progressEvent.loaded / costTime) * 1000; // 单位是 kb/s
      resolve({ costTime, speed: Math.floor(speed) });
    };

    await http.post(url, { file }, { headers: { "Content-Type": "multipart/form-data" }, onUploadProgress });
  });
};
